package com.digital.interceptor;

import com.digital.constant.JwtClaimsConstant;
import com.digital.constant.MessageConstant;
import com.digital.properties.JwtProperties;
import com.digital.result.Result;
import com.digital.utils.JwtUtil;
import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor
{
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod))
        {
            log.info("放行");
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //获取token
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        try
        {
            log.info("jwt校验:{}", token);
            Jws<Claims> claimsJws = JwtUtil.parseJWT(token, jwtProperties.getAdminSecretKey());
            Long adminId = Long.valueOf(claimsJws.getPayload().get(JwtClaimsConstant.ADMIN_ID).toString());
            log.info("当前管理员id:{}", adminId);
            log.info("放行");
            return true;
        }
        catch (Exception e)
        {
            Gson gson = new Gson();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(gson.toJson(Result.error(MessageConstant.NOT_LOGIN)));
            return false;
        }
    }
}
